// 圣经问答游戏 - 成就系统

class AchievementSystem {
    constructor() {
        this.achievements = {
            // 基础成就
            firstGame: {
                id: 'firstGame',
                name: '初学者',
                description: '完成第一次游戏',
                icon: '🌱',
                category: 'basic',
                condition: (stats, gameResult) => stats.gamesPlayed >= 1
            },
            
            firstCorrect: {
                id: 'firstCorrect',
                name: '第一步',
                description: '答对第一道题',
                icon: '✨',
                category: 'basic',
                condition: (stats, gameResult) => stats.totalCorrect >= 1
            },

            // 连击成就
            streak5: {
                id: 'streak5',
                name: '坚持不懈',
                description: '连续答对5题',
                icon: '🔥',
                category: 'streak',
                condition: (stats, gameResult) => gameResult && gameResult.maxStreak >= 5
            },

            streak10: {
                id: 'streak10',
                name: '势如破竹',
                description: '连续答对10题',
                icon: '⚡',
                category: 'streak',
                condition: (stats, gameResult) => gameResult && gameResult.maxStreak >= 10
            },

            streak15: {
                id: 'streak15',
                name: '无人能挡',
                description: '连续答对15题',
                icon: '🌟',
                category: 'streak',
                condition: (stats, gameResult) => gameResult && gameResult.maxStreak >= 15
            },

            // 准确率成就
            accuracy80: {
                id: 'accuracy80',
                name: '圣经学者',
                description: '单次游戏正确率达到80%',
                icon: '📚',
                category: 'accuracy',
                condition: (stats, gameResult) => gameResult && gameResult.accuracy >= 80
            },

            accuracy90: {
                id: 'accuracy90',
                name: '智慧之光',
                description: '单次游戏正确率达到90%',
                icon: '💡',
                category: 'accuracy',
                condition: (stats, gameResult) => gameResult && gameResult.accuracy >= 90
            },

            accuracy100: {
                id: 'accuracy100',
                name: '完美主义者',
                description: '单次游戏全部答对',
                icon: '⭐',
                category: 'accuracy',
                condition: (stats, gameResult) => gameResult && gameResult.accuracy === 100
            },

            // 难度成就
            explorerMaster: {
                id: 'explorerMaster',
                name: '探索大师',
                description: '探索者难度正确率达到90%',
                icon: '🌱',
                category: 'difficulty',
                condition: (stats, gameResult) => 
                    gameResult && gameResult.difficulty === 'explorer' && gameResult.accuracy >= 90
            },

            adventurerMaster: {
                id: 'adventurerMaster',
                name: '冒险专家',
                description: '冒险家难度正确率达到85%',
                icon: '⭐',
                category: 'difficulty',
                condition: (stats, gameResult) => 
                    gameResult && gameResult.difficulty === 'adventurer' && gameResult.accuracy >= 85
            },

            heroMaster: {
                id: 'heroMaster',
                name: '英雄大师',
                description: '英雄难度正确率达到80%',
                icon: '🏆',
                category: 'difficulty',
                condition: (stats, gameResult) => 
                    gameResult && gameResult.difficulty === 'hero' && gameResult.accuracy >= 80
            },

            legendMaster: {
                id: 'legendMaster',
                name: '传奇大师',
                description: '传奇难度正确率达到75%',
                icon: '👑',
                category: 'difficulty',
                condition: (stats, gameResult) => 
                    gameResult && gameResult.difficulty === 'legend' && gameResult.accuracy >= 75
            },

            // 探索成就
            allDifficulties: {
                id: 'allDifficulties',
                name: '全能选手',
                description: '尝试所有难度等级',
                icon: '🏅',
                category: 'exploration',
                condition: (stats, gameResult, gameHistory) => {
                    if (!gameHistory || gameHistory.length === 0) return false;
                    const difficulties = new Set(gameHistory.map(game => game.difficulty));
                    return difficulties.has('explorer') && difficulties.has('adventurer') && 
                           difficulties.has('hero') && difficulties.has('legend');
                }
            },

            // 数量成就
            questions50: {
                id: 'questions50',
                name: '勤学好问',
                description: '累计答题50道',
                icon: '📖',
                category: 'quantity',
                condition: (stats) => stats.totalQuestions >= 50
            },

            questions100: {
                id: 'questions100',
                name: '博学多才',
                description: '累计答题100道',
                icon: '🎓',
                category: 'quantity',
                condition: (stats) => stats.totalQuestions >= 100
            },

            questions500: {
                id: 'questions500',
                name: '知识渊博',
                description: '累计答题500道',
                icon: '📚',
                category: 'quantity',
                condition: (stats) => stats.totalQuestions >= 500
            },

            // 游戏次数成就
            games10: {
                id: 'games10',
                name: '热爱学习',
                description: '完成10次游戏',
                icon: '❤️',
                category: 'games',
                condition: (stats) => stats.gamesPlayed >= 10
            },

            games50: {
                id: 'games50',
                name: '持之以恒',
                description: '完成50次游戏',
                icon: '💪',
                category: 'games',
                condition: (stats) => stats.gamesPlayed >= 50
            },

            // 时间成就
            consecutive3Days: {
                id: 'consecutive3Days',
                name: '三日不辍',
                description: '连续3天游戏',
                icon: '📅',
                category: 'time',
                condition: (stats) => this.checkConsecutiveDays(stats.playDays, 3)
            },

            consecutive7Days: {
                id: 'consecutive7Days',
                name: '七日坚持',
                description: '连续7天游戏',
                icon: '🗓️',
                category: 'time',
                condition: (stats) => this.checkConsecutiveDays(stats.playDays, 7)
            },

            // 分数成就
            score500: {
                id: 'score500',
                name: '初露锋芒',
                description: '单次游戏得分达到500分',
                icon: '🥉',
                category: 'score',
                condition: (stats, gameResult) => gameResult && gameResult.score >= 500
            },

            score1000: {
                id: 'score1000',
                name: '出类拔萃',
                description: '单次游戏得分达到1000分',
                icon: '🥈',
                category: 'score',
                condition: (stats, gameResult) => gameResult && gameResult.score >= 1000
            },

            score1500: {
                id: 'score1500',
                name: '登峰造极',
                description: '单次游戏得分达到1500分',
                icon: '🥇',
                category: 'score',
                condition: (stats, gameResult) => gameResult && gameResult.score >= 1500
            },

            // 特殊成就
            speedRunner: {
                id: 'speedRunner',
                name: '闪电答题',
                description: '在60秒内完成一次游戏',
                icon: '⚡',
                category: 'special',
                condition: (stats, gameResult) => gameResult && gameResult.timeTaken <= 60
            },

            nightOwl: {
                id: 'nightOwl',
                name: '夜猫子',
                description: '在深夜(22:00-06:00)游戏',
                icon: '🦉',
                category: 'special',
                condition: () => {
                    const hour = new Date().getHours();
                    return hour >= 22 || hour <= 6;
                }
            },

            earlyBird: {
                id: 'earlyBird',
                name: '早起鸟',
                description: '在清晨(05:00-08:00)游戏',
                icon: '🐦',
                category: 'special',
                condition: () => {
                    const hour = new Date().getHours();
                    return hour >= 5 && hour <= 8;
                }
            }
        };

        this.categories = {
            basic: { name: '基础成就', color: '#3498db' },
            streak: { name: '连击成就', color: '#e74c3c' },
            accuracy: { name: '准确率成就', color: '#2ecc71' },
            difficulty: { name: '难度成就', color: '#9b59b6' },
            exploration: { name: '探索成就', color: '#f39c12' },
            quantity: { name: '数量成就', color: '#1abc9c' },
            games: { name: '游戏成就', color: '#34495e' },
            time: { name: '时间成就', color: '#e67e22' },
            score: { name: '分数成就', color: '#d35400' },
            special: { name: '特殊成就', color: '#8e44ad' }
        };
    }

    // 检查连续天数
    checkConsecutiveDays(playDays, requiredDays) {
        if (!playDays || playDays.length < requiredDays) return false;

        // 将日期字符串转换为Date对象并排序
        const dates = playDays.map(day => new Date(day)).sort((a, b) => b - a);
        
        let consecutiveCount = 1;
        let maxConsecutive = 1;

        for (let i = 1; i < dates.length; i++) {
            const diffDays = Math.floor((dates[i-1] - dates[i]) / (1000 * 60 * 60 * 24));
            
            if (diffDays === 1) {
                consecutiveCount++;
                maxConsecutive = Math.max(maxConsecutive, consecutiveCount);
            } else if (diffDays > 1) {
                consecutiveCount = 1;
            }
        }

        return maxConsecutive >= requiredDays;
    }

    // 检查并解锁成就
    checkAchievements(stats, gameResult = null, gameHistory = null) {
        const newAchievements = [];
        
        Object.values(this.achievements).forEach(achievement => {
            // 检查是否已经解锁
            if (gameStorage.isAchievementUnlocked(achievement.id)) {
                return;
            }

            // 检查解锁条件
            try {
                if (achievement.condition(stats, gameResult, gameHistory)) {
                    const isNew = gameStorage.unlockAchievement(achievement.id);
                    if (isNew) {
                        newAchievements.push(achievement);
                    }
                }
            } catch (error) {
                console.error(`检查成就 ${achievement.id} 时出错:`, error);
            }
        });

        return newAchievements;
    }

    // 获取所有成就列表
    getAllAchievements() {
        const unlockedAchievements = gameStorage.getAchievements();
        
        return Object.values(this.achievements).map(achievement => ({
            ...achievement,
            unlocked: !!unlockedAchievements[achievement.id],
            unlockedDate: unlockedAchievements[achievement.id]?.unlockedDate || null,
            category: this.categories[achievement.category]
        }));
    }

    // 按类别获取成就
    getAchievementsByCategory() {
        const achievements = this.getAllAchievements();
        const categorized = {};

        Object.keys(this.categories).forEach(categoryId => {
            categorized[categoryId] = {
                ...this.categories[categoryId],
                achievements: achievements.filter(a => a.category.name === this.categories[categoryId].name)
            };
        });

        return categorized;
    }

    // 获取成就统计
    getAchievementStats() {
        const achievements = this.getAllAchievements();
        const total = achievements.length;
        const unlocked = achievements.filter(a => a.unlocked).length;
        const percentage = Math.round((unlocked / total) * 100);

        const categoryStats = {};
        Object.keys(this.categories).forEach(categoryId => {
            const categoryAchievements = achievements.filter(a => 
                a.category.name === this.categories[categoryId].name
            );
            const categoryUnlocked = categoryAchievements.filter(a => a.unlocked).length;
            
            categoryStats[categoryId] = {
                total: categoryAchievements.length,
                unlocked: categoryUnlocked,
                percentage: categoryAchievements.length > 0 ? 
                    Math.round((categoryUnlocked / categoryAchievements.length) * 100) : 0
            };
        });

        return {
            total,
            unlocked,
            percentage,
            categories: categoryStats
        };
    }

    // 获取推荐成就（接近解锁的成就）
    getRecommendedAchievements(stats, gameHistory = null) {
        const recommendations = [];
        
        Object.values(this.achievements).forEach(achievement => {
            if (gameStorage.isAchievementUnlocked(achievement.id)) {
                return;
            }

            // 为不同类型的成就提供进度提示
            let progress = null;
            let tip = null;

            switch (achievement.id) {
                case 'questions50':
                    progress = Math.min(100, (stats.totalQuestions / 50) * 100);
                    tip = `还需答题 ${Math.max(0, 50 - stats.totalQuestions)} 道`;
                    break;
                case 'questions100':
                    progress = Math.min(100, (stats.totalQuestions / 100) * 100);
                    tip = `还需答题 ${Math.max(0, 100 - stats.totalQuestions)} 道`;
                    break;
                case 'games10':
                    progress = Math.min(100, (stats.gamesPlayed / 10) * 100);
                    tip = `还需完成 ${Math.max(0, 10 - stats.gamesPlayed)} 次游戏`;
                    break;
                case 'allDifficulties':
                    if (gameHistory) {
                        const difficulties = new Set(gameHistory.map(game => game.difficulty));
                        const completed = ['explorer', 'adventurer', 'hero', 'legend'].filter(d => difficulties.has(d));
                        progress = (completed.length / 4) * 100;
                        const missing = ['explorer', 'adventurer', 'hero', 'legend'].filter(d => !difficulties.has(d));
                        tip = missing.length > 0 ? `尝试${missing.join('、')}难度` : '';
                    }
                    break;
            }

            if (progress !== null && progress > 0 && progress < 100) {
                recommendations.push({
                    ...achievement,
                    progress: Math.round(progress),
                    tip,
                    category: this.categories[achievement.category]
                });
            }
        });

        // 按进度排序，进度高的在前
        return recommendations.sort((a, b) => b.progress - a.progress).slice(0, 5);
    }

    // 获取最近解锁的成就
    getRecentAchievements(limit = 5) {
        const unlockedAchievements = gameStorage.getAchievements();
        
        const recent = Object.entries(unlockedAchievements)
            .filter(([id, data]) => data.unlocked && data.unlockedDate)
            .map(([id, data]) => ({
                ...this.achievements[id],
                unlockedDate: data.unlockedDate,
                category: this.categories[this.achievements[id].category]
            }))
            .sort((a, b) => new Date(b.unlockedDate) - new Date(a.unlockedDate))
            .slice(0, limit);

        return recent;
    }

    // 生成成就分享文本
    generateShareText(achievement) {
        const messages = [
            `我在圣经问答游戏中获得了"${achievement.name}"成就！${achievement.icon}`,
            `解锁新成就：${achievement.name} ${achievement.icon} - ${achievement.description}`,
            `圣经问答游戏成就达成：${achievement.name} ${achievement.icon}`
        ];
        
        return messages[Math.floor(Math.random() * messages.length)];
    }
}

// 创建全局成就系统实例
window.achievementSystem = new AchievementSystem();